<?php

require_once(dirname(dirname(dirname(dirname(dirname(__FILE__))))) . '/appconf.php');
error_reporting(E_ALL);

class mapi_itrial_report extends Site {

    function setup() {
        $this->run_modes('list', 'add', 'edit', 'view_report_by_edit');
        $this->start_mode('list');
        parent::setup();
    }

    function cgiapp_prerun() {
        $this->ProductReports = getModel('Model_ProductReports');
        $this->Product = getModel('Model_Product');
        $this->Lookup = getModel('Model_Lookup');
        $this->mapi_object = getModel('MAPI_Base');
        $this->height = 163;
        $this->width = 102;
        $this->height_big = 800;
        $this->width_big = 800;
        parent::cgiapp_prerun();
    }

    function action_list() {
        $productId = $this->get_param('q', 'id', 0, 'int');
        $page = intval($this->get_q('page', 1, 'int'));
        $pagesize = intval($this->get_q('pagesize', 10, 'int'));
        $rid = $this->get_param('q', 'rid', 0, 'int');


        if (empty($productId) && empty($rid)) {
            $this->ajaxReturn(array(), array('retcode' => '0', 'msg' => '產品id 和 報告id 不能同時為空'));
        }

        $kvcobj = getCache('mapi_report_list', array('expire' => KVC_EXPIRE));
        $report_list = $kvcobj->get('mapi_report_list_' . $productId . "_" . $page . "_" . $pagesize . "_" . $rid);
        if (!$report_list) {

            $age = $this->Lookup->getLookup('agegroup');

            $agearr = array();
            if ($age['result']) {
                foreach ($age['result'] as $value) {
                    $agearr[$value['id']] = $value['name'];
                }
            }

            $h_param = array(
                'productId' => $productId,
                'page' => $page,
                'size' => $pagesize,
                'is_mobile' => 0,
                'is_publish' => 1,
                'reportsId' => $rid,
                'is_accept' => 1,
                'orderby' => 'TB1.priority desc,TB1.addtime desc',
            );
            $report_list = $this->ProductReports->h_get_reports_list($h_param);

            $a_result = array();

            $a_required_field = array('id', 'oid', 'mid', 'title', 'body', 'likes', 'well', 'category_score1', 'category_score2', 'category_score3', 'category_score4', 'category_score5', 'category_score6', 'category_score7', 'category_score8', 'is_accept', 'status', 'addtime', 'comments', 'click', 'member_type', 'is_blog', 'is_publish', 'lastmodify');

            if ($report_list['result']) {
                foreach ($report_list['result'] as $key => $value) {

                    $h_row = array();
                    foreach ($a_required_field as $field) {
                        $h_row[$field] = $value[$field];
                    }
                    $m_type = ($h_row['member_type'] == 5) ? "expert" : "trialist";
                    $h_row['share_url'] = $this->param('URL') . $m_type . "/report-detail-" . $h_row['oid'] . "-" . $h_row['id'] . ".html";
                    if ($value['content_json']) {
                        $a_content = array();
                        $a_json = json_decode($value['content_json'], 1);
                        if ($a_json) {
                            foreach ($a_json as $value_json) {
                                $arr = array();
                                //$arr['p'] = $url . showphotoCenter($www . $value['p'], $this->height, $this->width);
                                $arr['p'] = photoResize($value_json['p'], '300_200');
                                $arr['bp'] = photoResize($value_json['p'], '800_800');
                                $arr['t'] = $value_json['t'];
                                $a_content[] = $arr;
                            }
                        }
                    }

                    $h_row['content_array'] = $a_content;
                    $product = $this->Product->getProductById($value['oid']);
                    if (!empty($product['vote_option_data']['result'])) {
                        $vote_option_array = array();
                        foreach ($product['vote_option_data']['result'] as $k1 => $v1) {

                            $vote_option_array[$k1]['name'] = $v1['cname'];
                            $vote_option_array[$k1]['value'] = @$value['category_score' . ($k1 + 1)];
                        }
                    }
                    $h_row['vote_option_array'] = $vote_option_array;



                    $h_row_member = array();
                    $h_row_member['id'] = $value['mid'];
                    $h_row_member['username'] = $value['username'];
                    $h_row_member['photo_url'] = imore_avatar($value['photo']);
                    $h_row_member['agegroup'] = $agearr[getAgeGroup(getAge($value['birthday']))];
                    $h_row_member['face_skin'] = $value['body_skin'];

                    $a_result[$key]['report'] = $h_row;
                    $a_result[$key]['member'] = $h_row_member;
                }
            }

            $report_list['result'] = $a_result;

            $kvcobj->set('mapi_report_list_' . $productId . "_" . $page . "_" . $pagesize . "_" . $rid, $report_list);
        }

        return $this->mapi_object->to_json($report_list['result'], $report_list['pageinfo']);
    }

    function action_add() {

        $mid = intval($this->get_q('mid', 0, 'int'));
        $pid = intval($this->get_q('pid', 0, 'int'));
        $token = $this->get_q('token');
        if (!$mid || !$token || !$pid) {
            return $this->mapi_object->to_json(array(), array(), 0, "會員id，token，產品id不能為空");
        }

        $check_data = $this->check_member_submit($pid, $mid);
        sos(var_export($check_data, 1));
        if ($check_data['retcode'] == 0) {
            return $this->mapi_object->to_json(array(), array(), 0, $check_data['msg']);
        } else {
            $product = $check_data['product'];
            $mem_app = $check_data['mem_app'];
        }

        $h_param = array();
        $h_param['pid'] = $pid;
        $h_param['mid'] = $mid;
        $h_param['mem_app'] = $mem_app;
        $h_param['product'] = $product;
        $retunt_array = $this->submit_report($h_param);
        return $retunt_array;
    }

    function action_view_report_by_edit() {
        $rid = intval($this->get_q('rid', 0, 'int'));
        $pid = intval($this->get_q('pid', 0, 'int'));
        $mid = intval($this->get_q('mid', 0, 'int'));
        $token = $this->get_q('token');
        if (!$mid || !$token || !$pid || !$rid) {
            return $this->mapi_object->to_json(array(), array(), 0, "會員id，token，產品id，報告id不能為空");
        }

        $check_data = $this->check_member_submit($pid, $mid, 1, $rid);
        if ($check_data['retcode'] == 0) {
            return $this->mapi_object->to_json(array(), array(), 0, $check_data['msg']);
        } else {

            $product_report = $check_data['product_report'];
        }

        $product_report_res = !empty($product_report['result'][0]) ? $product_report['result'][0] : array();
        $a_required_field = array('id', 'oid', 'mid', 'title', 'agegroup', 'content_json', 'body', 'likes', 'well', 'category_score1', 'category_score2', 'category_score3', 'category_score4', 'category_score5', 'category_score6', 'category_score7', 'category_score8', 'is_accept', 'status', 'addtime', 'comments', 'body_skin_id', 'click', 'member_type', 'is_blog', 'username', 'is_publish', 'lastmodify');

        $h_row = array();
        foreach ($a_required_field as $field) {
            $h_row[$field] = $product_report_res[$field];
        }

        if ($h_row['content_json']) {
            $a_content = array();
            $a_json = json_decode($h_row['content_json'], 1);
            if ($a_json) {
                foreach ($a_json as $key => $value) {
                    $a_content[$key]['p'] = photoResize($value['p'], '300_200');
                    $a_content[$key]['bp'] = $value['p'];
                    $a_content[$key]['t'] = $value['t'];
                }
            }
        }
        $h_row['content_array'] = $a_content;

        unset($h_row['content_json']);

        return $this->mapi_object->to_json($h_row);
    }

    function action_edit() {
        $rid = intval($this->get_q('rid', 0, 'int'));
        $pid = intval($this->get_q('pid', 0, 'int'));
        $mid = intval($this->get_q('mid', 0, 'int'));
        $token = $this->get_q('token');
        if (!$mid || !$token || !$pid || !$rid) {
            return $this->mapi_object->to_json(array(), array(), 0, "會員id，token，產品id，報告id不能為空");
        }
        $check_data = $this->check_member_submit($pid, $mid, 1, $rid);
        if ($check_data['retcode'] == 0) {
            return $this->mapi_object->to_json(array(), array(), 0, $check_data['msg']);
        } else {
            $product = $check_data['product'];
            $mem_app = $check_data['mem_app'];
        }
        $h_param = array();
        $h_param['pid'] = $pid;
        $h_param['mid'] = $mid;
        $h_param['rid'] = $rid;
        $h_param['is_edit'] = 1;
        $h_param['mem_app'] = $mem_app;
        $h_param['product'] = $product;
        $retunt_array = $this->submit_report($h_param);
        return $retunt_array;
    }

    function submit_report($h_param = array()) {

        $pid = !empty($h_param['pid']) ? intval($h_param['pid']) : 0;
        $mid = !empty($h_param['mid']) ? intval($h_param['mid']) : 0;
        $mem_app = $h_param['mem_app'] ? $h_param['mem_app'] : array();
        $product = $h_param['product'] ? $h_param['product'] : array();
        $is_edit = !empty($h_param['is_edit']) ? intval($h_param['is_edit']) : 0;
        $rid = !empty($h_param['rid']) ? intval($h_param['rid']) : 0;

        $agegroup = "";
        $member = $this->getMember($mid);
        if ($member['result'])
            $agegroup = $member['result'][0]['agegroup'];

        $attr = array(
            'oid' => $pid,
            'mid' => $mid,
            'title' => htmlspecialchars($this->get_q('title', '')),
            'agegroup' => $agegroup,
            'body_skin' => 0,
            'well' => intval($this->get_q('well', 1, 'int')),
            'body' => htmlspecialchars($this->get_q('content', '')),
        );
        for ($i = 1; $i < 9; $i++) {
            $attr['category_score' . $i] = intval($this->get_q('category_score' . $i, 1, 'int'));
        }

        $pic_array = array();
        $pic_p = $this->get_q('pic_p', '');
        $pic_t = $this->get_q('pic_t', '');

        $pic_c = $this->get_q('pic_c', '');
        /*
          $pic_c_array = explode(",", $pic_c);

          $pic_p_array = explode(",", $pic_p);
          $pic_t_array = explode(",", $pic_t);
         */
        $pic_c_array = json_decode($pic_c, 1);
        $pic_p_array = json_decode($pic_p, 1);
        $pic_t_array = json_decode($pic_t, 1);

        if ($pic_p_array) {
            foreach ($pic_p_array as $key => $value) {
                $pic_array[$key]['p'] = $value;
                $pic_array[$key]['t'] = $pic_t_array[$key];
            }
        }


        $other = array(
            'pic' => $pic_array,
            'pic_c' => $pic_c_array,
            'body_size' => $this->get_q('content_size', 1, 'int'),
            'mem_app' => !empty($mem_app['result']) ? $mem_app['result'] : array(),
            'is_draft' => $this->get_q('is_draft', 0, 'int'),
        );

        $global_url = $this->param('URL');
        if ($is_edit) {
            $ret = $this->Product->report_add_submit_updb($attr, $other, $product, 1, $rid, $global_url);
        } else {
            $ret = $this->Product->report_add_submit_updb($attr, $other, $product, 0, 0, $global_url);
        }
        if (is_array($ret)) {
            if ($ret[2]['msg'] == 'success') {
                $return_array = array('retcode' => 1, 'msg' => "success");
                return $this->mapi_object->to_json(array(), array(), 1, "success");
            } else {
                $return_array = array('retcode' => 0, 'msg' => $ret[2]['msg']);
            }
        } else {
            $return_array = array('retcode' => 0, 'msg' => 'error');
        }
        return $return_array;
    }

    function check_member_submit($pid, $mid, $is_edit = 0, $rid = 0) {

        $product = $this->Product->get_product_byid($pid);
        $mem_app = db_query_one('member_application', array('field' => 'id,mid,product,is_submitted,rid,report_endtime,report_starttime', 'where' => 'product=' . $pid . ' and mid=' . $mid . ' and status=1'));

        if ($is_edit) {

            $h_param = array(
                'productId' => $pid,
                'reportsId' => $rid,
                'mid' => $mid,
                'page' => 1,
                'size' => 1,
                'orderby' => 'TB1.id desc',
                'is_accept' => 0,
                'keyword' => "",
                'trailist_report' => 0,
                'expert_report' => 0,
                'is_blog' => 2,
                'member_type_byclick' => 0,
                'is_mobile' => 1,
                'is_publish' => 0,
            );
            $product_report = $this->ProductReports->h_get_reports_list($h_param);

            $return_array = array('retcode' => 1, 'msg' => "ok", 'product' => $product, 'mem_app' => $mem_app, 'product_report' => $product_report);
        } else {
            $return_array = array('retcode' => 1, 'msg' => "ok", 'product' => $product, 'mem_app' => $mem_app);
        }

        if ($product['member_type'] == 5) {
            if (empty($mem_app['result'])) {
                $return_array = array('retcode' => 0, 'msg' => "抱歉！你沒有申請此項產品的試用,所以不能提交報告！");
            }
            if (!empty($mem_app['result']['is_submitted']) && $mem_app['result']['is_submitted'] == 1 && !$is_edit) {
                $return_array = array('retcode' => 0, 'msg' => "抱歉！您已提交此報告！");
            }
            if ((time() > (strtotime($mem_app['result']['report_endtime']) + 7 * 24 * 3600)) && !$is_edit) {
                $return_array = array('retcode' => 0, 'msg' => "抱歉！您已錯過提交報告時間！");
            }
        }

        if ($is_edit) {
            $start_time = $mem_app['result']['report_starttime'] ? $mem_app['result']['report_starttime'] : $product['report_starttime'];
            if (time() < strtotime($start_time)) {

                $return_array = array('retcode' => 0, 'msg' => "抱歉！活動時間有誤！");
            }


            if (empty($product_report['result'])) {
                $return_array = array('retcode' => 0, 'msg' => "抱歉！此報告不存在或狀態有誤！");
            }
        }
        return $return_array;
    }

}

header("Content-type: text/html; charset=utf-8");
$webapp = new mapi_itrial_report();
$webapp->run();
?>